<?php


namespace app\common\library;


use app\common\exception\BaseException;
use hiredis;

class DLock {

    var $key;
    var $timeout;

    function __construct($id, $time) {
        $this->key = 'CTX_LOCK_' . $id;
        $try_time = 0;
        $ok = false;
        $sleep_per_ms = 50;
        $try_time_max = $time * 1000 / $sleep_per_ms;
        $try_time_max = 1;
        while ($try_time < $try_time_max && !$ok) {
            $try_time++;
            $incr = hiredis::db()->incr($this->key);
            if ($incr != 1) {
                usleep($sleep_per_ms * 1000);
                continue;
            } else {
                hiredis::db()->expire($this->key, $time);
                $ok = true;
            }
        }

        if (!$ok) {
            throw new BaseException(['errorCode'=>X_ERROR, 'msg'=>'']);
        }
    }

    function __destruct() {
        hiredis::db()->delete($this->key);
    }

}
